﻿using Hidistro.Core;
using JSShop.Model;
using Juse.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using wnxd.javascript;

namespace Hidistro.UI.Web
{
    public class Generate : wnxd.Web.Interface
    {
        private ProductBrowser IProductBrowser = new ProductBrowser();
        private CategoryBrowser ICategoryBrowser = new CategoryBrowser();
        public bool generate_product(int ProductId = 0)
        {
            string wpath = HttpContext.Current.Server.MapPath("~/wnxd/");
            if (!Directory.Exists(wpath)) Directory.CreateDirectory(wpath);
            string status = this._ReadFile(wpath + "wnxd_generate_product.tmp");
            if (!string.IsNullOrEmpty(status) && status != "ok" && status != "fail") return false;
            int i = 0;
            string pdstr = "";
            Action<string, int> func = (fenlei, pid) =>
            {
                HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/ProductDetails.aspx?productId=" + pid);
                pdstr = Request.Address.ToString();
                Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36";
                using (WebResponse Response = Request.GetResponse())
                using (Stream resStream = Response.GetResponseStream())
                using (StreamReader sr = new StreamReader(resStream, Encoding.UTF8))
                {
                    string path = HttpContext.Current.Server.MapPath("~/" + fenlei);
                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                    File.WriteAllText(HttpContext.Current.Server.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { pid, fenlei })), sr.ReadToEnd());
                }
                this._WriteFile(wpath + "wnxd_generate_product.tmp", (++i).ToString());
            };
            try
            {

                this._WriteFile(wpath + "wnxd_generate_product.tmp", "0");
                if (ProductId == 0)
                {
                    List<vw_Hishop_BrowseProductList> list = IProductBrowser.GetAllProductView();
                    this._WriteFile(wpath + "wnxd_product_num.tmp", list.Count.ToString());
                    foreach (vw_Hishop_BrowseProductList info in list)
                    {
                        if (info.SaleStatus == JSShop.Enum.ProductSaleStatus.OnSale)
                        {
                            ProductId = info.ProductId;
                            func(info.CategoryUrl, ProductId);
                        }                 
                    }
                }
                else
                {
                    vw_Hishop_BrowseProductList info = IProductBrowser.GetBrowseProductView(null, ProductId);
                    func(info.CategoryUrl, ProductId);
                }
            }
            catch (Exception ex)
            {
                string aa = pdstr;
                this._WriteFile(wpath + "wnxd_generate_product.tmp", aa);
                StringBuilder str = new StringBuilder();
                str.AppendLine("----------------商品生成--------------------------------------------------------------------------");
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
                if (!Directory.Exists(upLoadPath))
                {
                    Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    FileInfo fileInfo = new FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                return false;
            }
            this._WriteFile(wpath + "wnxd_generate_product.tmp", "ok"); ;
            return true;
        }
        public bool generate_category(int CategoryId = 0)
        {
            string wpath = HttpContext.Current.Server.MapPath("~/wnxd/");
            if (!Directory.Exists(wpath)) Directory.CreateDirectory(wpath);
            string status = this._ReadFile(wpath + "wnxd_generate_category.tmp");
            if (!string.IsNullOrEmpty(status) && status != "ok" && status != "fail") return false;
            Type T = typeof(HttpRequest);
            FieldInfo _url = T.GetField("_url", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo _rawUrl = T.GetField("_rawUrl", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            object old_url = _url.GetValue(HttpContext.Current.Request);
            object old_RawUrl = _rawUrl.GetValue(HttpContext.Current.Request);
            int i = 0;
            Action<string, int> func = (fenlei, cid) =>
            {
                using (TextWriter tw = new StringWriter())
                {
                    _url.SetValue(HttpContext.Current.Request, new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/SubPage_new.aspx?CategoryId=" + cid));
                    _rawUrl.SetValue(HttpContext.Current.Request, Globals.GetSiteUrls().UrlData.FormatUrl("subCategory_Rewrite", new object[] { fenlei }));
                    HttpContext.Current.Server.Execute("/SubPage_new.aspx?CategoryId=" + cid, tw, false);
                    string path = HttpContext.Current.Server.MapPath("~/" + fenlei);
                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                    File.WriteAllText(HttpContext.Current.Server.MapPath("~" + HttpContext.Current.Request.RawUrl + "index.html"), tw.ToString());
                    this._WriteFile(wpath + "wnxd_generate_category.tmp", (++i).ToString());
                }
            };
            try
            {
                this._WriteFile(wpath + "wnxd_generate_category.tmp", "0");
                if (CategoryId == 0)
                {
                    List<Hishop_Categories> list = ICategoryBrowser.GetSubCategories(0, 0);
                    this._WriteFile(wpath + "wnxd_category_num.tmp", list.Count.ToString());
                    foreach (Hishop_Categories info in list)
                    {
                        CategoryId = info.CategoryId;
                        func(info.RewriteName, CategoryId);
                    }
                }
                else
                {
                    Hishop_Categories info = ICategoryBrowser.GetCategoryInfo(CategoryId);
                    func(info.RewriteName, CategoryId);
                }
            }
            catch (Exception ex)
            {
                this._WriteFile(wpath + "wnxd_generate_category.tmp", "fail");
                StringBuilder str = new StringBuilder();
                str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
                if (!Directory.Exists(upLoadPath))
                {
                    Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    FileInfo fileInfo = new FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                _url.SetValue(HttpContext.Current.Request, old_url);
                _rawUrl.SetValue(HttpContext.Current.Request, old_RawUrl);
                return false;
            }
            this._WriteFile(wpath + "wnxd_generate_category.tmp", "ok");
            _url.SetValue(HttpContext.Current.Request, old_url);
            _rawUrl.SetValue(HttpContext.Current.Request, old_RawUrl);
            return true;
        }
        public bool generate_common(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return false;
            try
            {
                Type T = typeof(HttpRequest);
                FieldInfo _url = T.GetField("_url", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo _rawUrl = T.GetField("_rawUrl", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                if (url.First() != '/') url = "/" + url;
                using (TextWriter tw = new StringWriter())
                {
                    _url.SetValue(HttpContext.Current.Request, new Uri(url));
                    _rawUrl.SetValue(HttpContext.Current.Request, url);
                    HttpContext.Current.Server.Execute(url, tw, true);
                    string path = HttpContext.Current.Server.MapPath("~" + url);
                    this._WriteFile(Path.GetDirectoryName(path) + "/" + Path.GetFileNameWithoutExtension(path) + ".html", tw.ToString());
                }
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
                if (!Directory.Exists(upLoadPath))
                {
                    Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    FileInfo fileInfo = new FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                return false;
            }
            return true;
        }
        public bool delete_product(int ProductId)
        {
            if (ProductId != 0)
            {
                try
                {
                    vw_Hishop_BrowseProductList info = IProductBrowser.GetBrowseProductView(null, ProductId);
                    File.Delete(HttpContext.Current.Server.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { ProductId, info.CategoryUrl })));
                    return true;
                }
                catch
                {

                }
            }
            return false;
        }
        public bool delete_category(int CategoryId)
        {
            if (CategoryId != 0)
            {
                try
                {
                    Hishop_Categories info = ICategoryBrowser.GetCategoryInfo(CategoryId);
                    File.Delete(HttpContext.Current.Server.MapPath("~" + Globals.GetSiteUrls().UrlData.FormatUrl("subCategory_Rewrite", new object[] { info.RewriteName }) + "index.html"));
                    return true;
                }
                catch
                {

                }
            }
            return false;
        }
        public json query_product()
        {
            string wpath = HttpContext.Current.Server.MapPath("~/wnxd/");
            string status = this._ReadFile(wpath + "wnxd_generate_product.tmp");
            return new json(new { now = status, total = this._ReadFile(wpath + "wnxd_product_num.tmp") });
        }
        public json query_category()
        {
            string wpath = HttpContext.Current.Server.MapPath("~/wnxd/");
            string status = this._ReadFile(wpath + "wnxd_generate_category.tmp");
            return new json(new { now = status, total = this._ReadFile(wpath + "wnxd_category_num.tmp") });
        }
        public bool stop_product()
        {
            try
            {
                File.Delete(HttpContext.Current.Server.MapPath("~/wnxd/wnxd_generate_product.tmp"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool stop_category()
        {
            try
            {
                File.Delete(HttpContext.Current.Server.MapPath("~/wnxd/wnxd_generate_category.tmp"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool template(string domain, string url)
        {
            if (string.IsNullOrWhiteSpace(domain)) return this.generate_common(url);
            if (string.IsNullOrWhiteSpace(url)) return false;
            try
            {
                if (domain.Last() != '/') domain += "/";
                if (url.First() == '/') url = url.Substring(1);
                HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(domain + url);
                Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36";
                using (WebResponse Response = Request.GetResponse())
                using (Stream resStream = Response.GetResponseStream())
                using (StreamReader sr = new StreamReader(resStream, Encoding.UTF8))
                {
                    string path = HttpContext.Current.Server.MapPath("~/" + url);
                    this._WriteFile(Path.GetDirectoryName(path) + "/" + Path.GetFileNameWithoutExtension(path) + ".html", sr.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("----------------分类生成--------------------------------------------------------------------------");
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
                if (!Directory.Exists(upLoadPath))
                {
                    Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    FileInfo fileInfo = new FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                return false;
            }
            return true;
        }
        private void _OnInit(Control control)
        {
            Type T = control.GetType();
            MethodInfo mi = T.GetMethod("OnInit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (mi != null) mi.Invoke(control, new object[] { new EventArgs() });
            for (int i = 0; i < control.Controls.Count; i++) this._OnInit(control.Controls[i]);
        }
        private void _EnsureChildControls(Control control)
        {
            Type T = control.GetType();
            MethodInfo mi = T.GetMethod("EnsureChildControls", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (mi != null) mi.Invoke(control, null);
            for (int i = 0; i < control.Controls.Count; i++) this._EnsureChildControls(control.Controls[i]);
        }
        private string _ReadFile(string path)
        {
            string res;
            try
            {
                if (!File.Exists(path)) return null;
                using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
                using (StreamReader sr = new StreamReader(fs))
                {
                    res = sr.ReadToEnd();
                }
            }
            catch
            {
                res = _ReadFile(path);
            }
            return res;
        }
        private void _WriteFile(string path, string contents)
        {
            try
            {
                using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(contents);
                    sw.Flush();
                }
            }
            catch
            {
                _WriteFile(path, contents);
            }
        }
    }
}
